#ifndef SESSION_H
#define SESSION_H
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include "Message.h"

using boost::asio::ip::tcp;
using namespace boost::asio;
using namespace boost;
///Session.
class Session:public boost::enable_shared_from_this<Session>
{
public:
	/** */
	Session(boost::asio::io_service& io_service,checkfuntype fun): socket_(io_service),valid(false),fun_(fun)
	{
	}
/** */
	tcp::socket& socket()
	{
		return socket_;
	}
	/** */
	void start()
	{
		LoginMessage& temp=readLoginMessage();
		LoginMessage result;
		if (fun_(temp.username,temp.password))
		{
			valid=true;
			result.result[0]='o';
			result.result[1]='k';
			result.result[2]='\0';
			
			writeLoginMessage(result);
		}else
		{
			result.result[0]='f';
			result.result[1]='a';
			result.result[2]='i';
			result.result[3]='l';
			result.result[4]='\0';
			writeLoginMessage(result);
		}
	}
	/** */
	void do_nothing(){}
	void writeLoginMessage(LoginMessage& m)
	{
		boost::asio::write(socket_,buffer(&m,sizeof(LoginMessage)));
	}
	/** */
	LoginMessage readLoginMessage()
	{
		char buf[sizeof(LoginMessage)];
		boost::asio::read(socket_,buffer(buf,sizeof(LoginMessage)));
		return *((LoginMessage*)buf);
	}
	/** */
	void async_write(MyMsg& m)
	{
		boost::asio::async_write(socket_,buffer(&m,sizeof(MyMsg)),boost::bind(&Session::do_nothing,shared_from_this()));
	}
	/** */
	bool isValid(){return valid;}
private:
	tcp::socket socket_;
	bool valid;
	checkfuntype fun_;
};

typedef boost::shared_ptr<Session> SharedSession;


#endif